<template>
  <batchUpdateValueDialog
    :dialogInfo="batchUpdateValueDialogInfo"
    @baseMounted="baseMounted"
    :self="self">
  </batchUpdateValueDialog>
  <setTablesDialog
    :dialogInfo="setTablesDialogInfo"
    @baseMounted="baseMounted"
    :self="self">
  </setTablesDialog>
  <batchEditDialog
    :dialogInfo="batchEditDialogInfo"
    @baseMounted="baseMounted"
    :self="self">
  </batchEditDialog>
</template>

<script>
import { ref, unref, watch, onMounted } from 'vue'
import { post } from "/src/api/index";
import batchUpdateValueDialog from '../edit_dialog.vue'
import setTablesDialog from '../edit_dialog.vue'
import batchEditDialog from '../edit_dialog.vue'
import { ElMessage } from '/src/utils'

export default {
    emits: ['baseMounted'],
    components:{
      batchUpdateValueDialog,
      setTablesDialog,
      batchEditDialog,
    },
    props: {
      self:{},
    },
    setup(prop,context) {

      const batchEditDialogInfo = ref({
        title: '批量编辑',
        visible:false,
        loading: false,
        labelWidth: '400px',
        rules:[],
        form:{},
        columns:[
        ],
        onInit: param => {
            const {mode, form, column, columns, get_remote_list, dialogInfo} = param
        },
        onconfirm: (param) => {
          let {dialogInfo, selectRows} = param
          let changedForm = {}
          for(let p in {...dialogInfo.form_ori, ...dialogInfo.form}) {
            if(dialogInfo.form_ori[p] != dialogInfo.form[p]) {
              changedForm[p] = dialogInfo.form[p]
            }
          }

          let prefix_same = ''
          let prefix_changed = ''
          let prefix_changed_dest = ''
          let prefix_append = ''
          if(dialogInfo.title.indexOf('添加') >= 0) {
            if(!changedForm.workspace_name && !changedForm.name) {
              ElMessage.error('添加时必须修改工作区或名称')
              return;
            }
          }
          if(changedForm.name && selectRows.length > 1) {
            if(changedForm.name.indexOf(dialogInfo.form_ori.name) == 0) {
              prefix_same = '*'
              prefix_append = changedForm.name.substring(dialogInfo.form_ori.name.length, 100)
            } else {
              for(let i = 0; i < dialogInfo.form_ori.name.length && i < changedForm.name.length; i++) {
                if(dialogInfo.form_ori.name.substring(i, i+1) == changedForm.name.substring(i, i+1)) {
                  prefix_same += dialogInfo.form_ori.name.substring(i, i+1)
                  continue
                }
                break;
              }
              if(prefix_same) {
                for(let i = prefix_same.length; i < dialogInfo.form_ori.name.length; i++) {
                  prefix_changed += dialogInfo.form_ori.name.substring(i, i+1)
                }
                for(let i = prefix_same.length; i < changedForm.name.length; i++) {
                  prefix_changed_dest += changedForm.name.substring(i, i+1)
                }
              }
              for(let row in selectRows) {
                row = selectRows[row]
                // if(prefix_same && row.name.indexOf(prefix_same) != 0) {
                //   ElMessage.error('多条批量添加时所有记录的名称必须有相同前缀：'+prefix_same)
                //   return;
                // }
                if(prefix_changed && row.name.lastIndexOf(prefix_changed) != row.name.length - prefix_changed.length) {
                  ElMessage.error('多条批量添加时所有记录的名称被修改部分必须保持一致，且仅可修改前缀或后缀：'+prefix_changed)
                  return;
                }
              }
            }
            // if(!prefix_same && !tail_same && selectRows.length > 1) {
            //   ElMessage.error('多条批量添加时修改工作区名称必须前缀一致或后缀一致')
            //   return;
            // }
            if(!prefix_same) {
              ElMessage.error('多条批量添加时，仅可修改后缀')
              return;
            }
          }

          let count = 0;
          selectRows.forEach( item => {
            let method = 'update'
            let destItem =  {id: item.id}
            if(dialogInfo.title.indexOf('添加') >= 0) {
              destItem = {...item}
              delete destItem.id
              method = 'add'
            }
            for(let p in changedForm) {
              destItem[p] = changedForm[p]
            }
            if(prefix_same) {
              if(prefix_same == '*') {
                destItem.name = item.name + prefix_append
              } else {
                destItem.name = item.name.substring(0, item.name.length - prefix_changed.length) + prefix_changed_dest
              }
            }
            post('sdp_project', method, destItem)
            .then( data => {
              count++;
              if (count == selectRows.length) {
                ElMessage.success('成功')
                prop.self.handleSearch();
                dialogInfo.hide(param)
                dialogInfo.loading = false;
              }
            })
            .catch( err => {
              ElMessage.error('失败')
              dialogInfo.loading = false;
            })
          })
        },
        hide: (param) => {
          const {dialogInfo} = param
          dialogInfo.form = {}
          dialogInfo.visible = false
          dialogInfo.loading = false
        },
        show: (param) => {
          let {dialogInfo, query, selectRows} = param

          selectRows = unref(selectRows)
          if (!selectRows || !selectRows.length) {
            ElMessage.error('请选择至少一条记录进行操作')
            return;
          }

          dialogInfo.columns = [...(unref(param.editColumns))]

          prop.self.init_remote_list(dialogInfo.columns, {query: unref(dialogInfo).form})

          dialogInfo.columns.forEach( item => {
            if (item.oninit) {
              item.oninit({...unref(prop.self), mode: 'init', dialogInfo:dialogInfo, column:item, columns: dialogInfo.columns, form: dialogInfo.form})
            }
          })

          dialogInfo.visible = true
          dialogInfo.title = '批量编辑'
        },
        edit2add:(param) => {
          let {dialogInfo, query, selectRows} = param
          dialogInfo.title = '批量添加'

        },
      })

      let setTablesDialogInfo = ref({
        title: '设置表及别名：【表注释（表名）】 - 【是否生成代码】 - 【别名】',
        visible:false,
        loading: false,
        labelWidth: '400px',
        rules:[],
        form:{},
        columns:[
        ],
        onconfirm: (param) => {
          let {dialogInfo, selectRows} = param
          let tables = ''
          let form = dialogInfo.form
          let tableList = []
          dialogInfo.columns.forEach( column => {
            if (form[column.prop+'_active']) {
              let alias = form[column.prop+'_alias']
              if (alias) {
                alias = alias.trim()
              }
              if (tables) {
                tables += ','
              }
              if (alias && alias != column.prop) {
                tables += column.prop + ' as ' + alias
              } else {
                tables += column.prop
              }
              if (form[column.prop+'_ignore_no_generate']) {
                tables += '-1';
              }
            }
          })
          let count = 0;
          selectRows.forEach( item => {
            post('sdp_project', 'update', {id:item.id, tables:tables})
            .then( data => {
              count++;
              if (count == selectRows.length) {
                ElMessage.success('更新成功')
                prop.self.handleSearch();
                dialogInfo.hide(param)
                dialogInfo.loading = false;
              }
            })
            .catch( err => {
              ElMessage.error('更新失败')
              dialogInfo.loading = false;
            })
          })
        },
        hide: (param) => {
          const {dialogInfo} = param
          dialogInfo.form = {}
          dialogInfo.visible = false
          dialogInfo.loading = false
        },
        show: (param) => {
          let {dialogInfo, query, selectRows} = param

          selectRows = unref(selectRows)
          if (!selectRows || !selectRows.length) {
            ElMessage.error('请选择至少一条记录进行操作')
            return;
          }

          dialogInfo.columns.forEach( item => {
            if (item.oninit) {
              item.oninit({...unref(prop.self), mode: 'init', dialogInfo:dialogInfo, column:item, columns: dialogInfo.columns, form: dialogInfo.form})
            }
          })

          dialogInfo.visible = true
        },
      })
      prop.self.setTablesDialogInfo = setTablesDialogInfo
      prop.self.batchEditDialogInfo = batchEditDialogInfo
      
        const baseMounted = (v) => {
        }

        return {
          batchUpdateValueDialogInfo: prop.self.batchUpdateValueDialogInfo,
          setTablesDialogInfo,
          batchEditDialogInfo,
          baseMounted,
        };
    },
};
</script>

<style scoped>

</style>
